package com.zff.rental.config.interceptor;

import com.zff.rental.tools.JwtTools;
import com.zff.rental.tools.UserContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 保存上下文（用户名，token）信息
 *
 * @author HCY
 */
public class SaveUserContextInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        // 保存上下文UserId
        String token = JwtTools.getTokenByServletRequest(request);
        if (!ObjectUtils.isEmpty(token)) {
            Long userId = JwtTools.getUserId(token);
            UserContextHolder.setUserId(userId);
            UserContextHolder.setToken(token);
        } else {
            UserContextHolder.clear();
        }
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex) {
        UserContextHolder.clear();
    }
}
